package company.duxiaoman;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Du2 {

    static int min;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int count = sc.nextInt();
        sc.nextLine();
        List<Integer> ans = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            min = Integer.MAX_VALUE;
            int n = sc.nextInt();
            int m = sc.nextInt();
            sc.nextLine();
            char[][] array = new char[n][m];
            int startX = 0, startY = 0;
            for (int j = 0; j < n; j++) {
                String tmp = sc.nextLine();
                for (int k = 0; k < m; k++) {
                    if (tmp.charAt(k) == '@') {
                        startX = k;
                        startY = j;
                    }
                    array[j][k] = tmp.charAt(k);
                }
            }
            helper(array, n, m, startX, startY, 0, new int[n][m]);
            ans.add(min == Integer.MAX_VALUE ? -1 : min);
        }
        for (Integer i : ans) {
            System.out.println(i);
        }
    }

    private static void helper(char[][] array, int n, int m, int x, int y, int count, int[][] used) {
        if (x < 0 || x >= m || y < 0 || y >= n)
            return;
        if (used[y][x] == 1)
            return;
        if (array[y][x] == '#')
            return;
        if (array[y][x] == '*')
            count += 1;
        if (x == 0 || x == m - 1) {
            min = Math.min(count, min);
            return;
        }
        if (y == 0 || y == n - 1) {
            min = Math.min(count, min);
            return;
        }
        used[x][y] = 1;
        helper(array, n, m, x + 1, y, count, used);
        helper(array, n, m, x - 1, y, count, used);
        helper(array, n, m, x, y + 1, count, used);
        helper(array, n, m, x, y - 1, count, used);
        used[x][y] = 0;
    }

}
